<template>
  <div class="password">
    <input
      v-for="(item, index) in codeArr"
      :key="index"
      type="text"
      class="input"
      maxlength="1"
      v-model="codeArr[index]"
      @input="onInput(index)"
      @keydown.backspace="onBackspace(index, $event)"
      @focus="onFocus(index)"
      ref="inputs"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, defineEmits } from 'vue'

const emits = defineEmits(['inputComplete'])

const codeArr = ref(['', '', '', '', '', ''])
const inputs = ref([])

const onInput = (index) => {
  if (codeArr.value[index].length > 1) {
    codeArr.value[index] = codeArr.value[index].slice(0, 1)
  }

  for (let i = 0; i < index; i+=1) {
    if (!codeArr.value[i]) {
      codeArr.value[index] = ''
      return
    }
  }

  if (index < 5 && codeArr.value[index]) {
    nextTick(() => {
      inputs.value[index + 1]?.focus()
    })
  }

  // ✅ 如果全部输入完毕，则触发 inputComplete 事件
  if (codeArr.value.every(char => char !== '')) {
    emits('inputComplete', codeArr.value.join(''))
  }
}


const onBackspace = (index, event) => {
  if (!codeArr.value[index] && index > 0) {
    codeArr.value[index - 1] = ''
    nextTick(() => {
      inputs.value[index - 1]?.focus()
    })
  }
}

const onFocus = (index) => {
  // 禁止跳着点：如果前面有空的，就跳回第一个空的
  for (let i = 0; i < index; i+=1) {
    if (!codeArr.value[i]) {
      nextTick(() => {
        inputs.value[i]?.focus()
      })
      break
    }
  }
}
</script>

<style scoped>
.code-container {
  display: flex;
  gap: 8px;
}
.input {
  width: 40px;
  height: 40px;
  text-align: center;
  font-size: 18px;
}
.password {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    padding: 20px 0 0 0;
  }
  .password input {
    width: 20px;
    height: 30px;
    text-align: center;
    background-color: transparent;
    border: none;
    border-bottom: solid 2px rgb(20, 181, 230);
    font-size: 18px;
    color: white;
    outline: none;
  }
</style>
